package kr.co.bettersoft.waitnumbercustomer.fragment;


import com.google.android.gcm.GCMRegistrar;

import kr.co.bettersoft.waitnumbercustomer.common.CommonConstant;
import kr.co.bettersoft.waitnumbercustomer.activity.DummyActivity;
import kr.co.bettersoft.waitnumbercustomer.activity.GCMIntentService;
import kr.co.bettersoft.waitnumbercustomer.activity.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/**
 * 메인 화면이다. 이 위에 들이 fragment menu 에 의해 선택된 fragment 들이 보여진다. 
 * @author blue
 *
 */
public class FragmentHome extends FragmentActivity{
	static String TAG = "FragmentHome";
	
//	Typeface.createFromAsset(AssetManager, String); 
//	TextView.setTypeface(Typeface);
	
//	gNanumGothic = Typeface.createFromAsset(context.getAssets(), "fonts/heum.ttf");
//	gNanumGothic = Typeface.createFromAsset(context.getAssets(), "fonts/nanumgothic.ttf");
	
	//gcm
	AsyncTask<Void, Void, Void> mRegisterTask;
	public static String REGISTRATION_ID = "";		// 등록아이디
	
	// 설정 파일 저장소 
	SharedPreferences sharedPrefCustom;
	String memberId;		// pref 에 들어있는 고객 아이디
	
	Button myQrScreenBtn;
	Button waitUserListBtn;
	Button memberStoreListBtn;
	Button settingsBtn;
	
	public static int restCallCnt = 0; 
	// 뒤로가기 버튼으로 닫을때 2번만에 닫히도록
	static int app_end = 0;			
	DummyActivity dummyActivity = (DummyActivity)DummyActivity.dummyActivity;
	
	int nowMenuPostion = 0;
	Boolean isSame = false;
////////////////////////////////////////////////////////////////////////////////////////////////////
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.fragment_main);
		
		checkNetworkContinue();
		
		// prefs
		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		memberId = sharedPrefCustom.getString("qrCode", "");	
		
		gcmReg();
		
		myQrScreenBtn = (Button) findViewById(R.id.my_qr_screen_btn);
		waitUserListBtn = (Button) findViewById(R.id.wait_user_list_btn);
		memberStoreListBtn = (Button) findViewById(R.id.member_store_list_btn);
		settingsBtn = (Button) findViewById(R.id.settings_btn);
		
		myQrScreenBtn.setOnClickListener(onBtnClickListener);
		waitUserListBtn.setOnClickListener(onBtnClickListener);
		memberStoreListBtn.setOnClickListener(onBtnClickListener);
		settingsBtn.setOnClickListener(onBtnClickListener);
		
		showDetailFragment("MyQRScreen");
	}
	
	public void gcmReg(){
////////////////////////////////////////////GCM 세팅        ///////////////////////////////////////////////////////////////		
		GCMRegistrar.checkDevice(this);					// 임시 중지  ->해제
		GCMRegistrar.checkManifest(this);				
		Log.i(TAG, "registerReceiver1 ");
		mRegisterTask = new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {	// 무조건 GCM 등록한다. 이전값이든 새값이든 등록하고 //등록 결과를 서버에 업뎃하는 부분은 GCM서비스에서 처리한다.
				GCMIntentService.myQR = memberId;
				GCMRegistrar.register(returnThis(), CommonConstant.SENDER_ID);	
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				mRegisterTask = null;
			}
		};
		mRegisterTask.execute(null, null, null);
	}
	
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	private void showDetailFragment(String $tag)
	{
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment newFragment = new MyQRScreenFragment();
		
		if ($tag.contains("MyQRScreen")) {
			if(nowMenuPostion!=1){
				nowMenuPostion = 1;
				myQrScreenBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_3_over));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_4));
				memberStoreListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_5));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_6));
				newFragment = new MyQRScreenFragment();			
				isSame = false;
			}else{
				isSame = true;
			}
				
		}else if($tag.contains("WaitUserList")){
			if(nowMenuPostion!=2){
				nowMenuPostion = 2;
				myQrScreenBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_3));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_4_over));
				memberStoreListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_5));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_6));
				newFragment = new WaitUserListFragment();
				isSame = false;
			}else{
				isSame = true;
			}
			
		}else if($tag.contains("MemberStoreList")){
			if(nowMenuPostion!=3){
				nowMenuPostion = 3;
				myQrScreenBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_3));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_4));
				memberStoreListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_5_over));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_6));
				newFragment = new MemberStoreListFragment();
				isSame = false;
			}else{
				isSame = true;
			}
		}else if($tag.contains("Settings")){
			if(nowMenuPostion!=4){
				nowMenuPostion = 4;
				myQrScreenBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_3));
				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_4));
				memberStoreListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_5));
				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub3_6_over));
				newFragment = new SettingsFragment();
				isSame = false;
			}else{
				isSame = true;
			}
		}
		
		if(!isSame){
			ft.replace(R.id.details, newFragment);								// fragment_main 의 detail 자리에 넣음
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			ft.commit();
		}
	}
	
	private OnClickListener onBtnClickListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			showDetailFragment(v.getTag().toString());
		}
	};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 통신 유지.
	public void checkNetworkContinue(){
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
//						Log.d(TAG,"sleep 2");
//						Thread.sleep(5000);
//						checkNetwork();
						
						ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
						  NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
						  boolean isWifiAvail = ni.isAvailable();
						  boolean isWifiConn = ni.isConnected();
						  ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
						  boolean isMobileAvail = ni.isAvailable();
						  boolean isMobileConn = ni.isConnected();
						  String status = "WiFi Avail = " + isWifiAvail + "// WiFi Conn = "
						    + isWifiConn + "// Mobile // Avail = " + isMobileAvail
						    + "// Conn = " + isMobileConn;
//						  Log.d(TAG,"status:"+status);
						Thread.sleep(5000);
						checkNetworkContinue();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
	}
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	public Context returnThis(){
		return this;
	}
	
	
	public static Boolean restCallCntUp(){
		Boolean cntResult = false;
		restCallCnt = restCallCnt +1;
		Log.d(TAG,"restCallCnt:"+restCallCnt);
		if(restCallCnt==1){
			cntResult = true;
		}else{
			restCallCnt = restCallCnt -1;
			cntResult = false;
		}
		return cntResult;
	}
	public static Boolean restCallCntDown(){
		Boolean cntResult = false;
		restCallCnt = restCallCnt -1;
		Log.d(TAG,"restCallCnt:"+restCallCnt);
		if(restCallCnt==0){
			cntResult = true;
		}else{
			cntResult = false;
		}
		return cntResult;
	}
	
	/*
	 *  닫기 버튼 2번 누르면 종료 됨.(non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	/**
	 * onBackPressed
	 *   닫기 버튼 2번 누르면 종료 한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onBackPressed() {
		Log.d(TAG, "FragmentHome finish");		
		if(app_end == 1){
			Log.d(TAG,"kill all");
			DummyActivity.count = 0;		// 개수 0으로 초기화 시켜준다. 다시 실행될수 있도록
			finish();
		}else{
			app_end = 1;
			Toast.makeText(FragmentHome.this, R.string.noti_back_finish, Toast.LENGTH_SHORT).show();
			new Thread( 
					new Runnable(){
						public void run(){
							try {
								Thread.sleep(3000);
								app_end = 0;
							} catch (InterruptedException e) {e.printStackTrace();}
						}
					}
			).start();
		}
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		System.exit(0);
	}
	
}
